package com.fly.controller;

import com.fly.dto.MyFileInfo;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {
    // 文件上传
    @PostMapping
    public MyFileInfo upload(MultipartFile file) throws Exception {
        System.out.println("上传的文件名:" + file.getName());
        System.out.println("原始文件名:" + file.getOriginalFilename());
        System.out.println(file.getSize());
        File localFile = new File("C:\\uploads", new Date().getTime() + ".txt");
        file.transferTo(localFile);
        return new MyFileInfo(localFile.getAbsolutePath());
    }

    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try (InputStream is = new FileInputStream(new File("C:\\uploads", id + ".txt"));
             OutputStream os = response.getOutputStream();) {
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=test.txt"); //下载时的文件名为test.txt
            IOUtils.copy(is, os);
            os.flush();
        }
    }
}
